﻿using Jay.Sc2.Bof.Lib.State;

namespace Jay.Sc2.Bof.Lib.Action.Zerg
{
	public abstract class ActionProduceFromDrone : ActionProduceZerg
	{
		public ActionProduceFromDrone(int buildTime, int minerals, int gas) : base(buildTime, minerals, gas, 0) { }

		public override int AvailableProducer(IBuildOrder bo)
		{
			ZergState state = bo.State as ZergState;
			return state.WorkersOnMinerals + state.WorkersOnGas;
		}

		public abstract ZergState.ZergBuilding GetBuilding(ZergState state);
		public abstract string EventName { get; }
		public override bool IsInvalid(IBuildOrder bo)
		{
			ZergState state = bo.State as ZergState;
			return base.IsInvalid(bo) || state.Drone + state.Drone_Building == 0;
		}
		public override void Execute(IBuildOrder bo)
		{
			ZergState state = bo.State as ZergState;
			if (state.WorkersOnMinerals > 0)
			{
				state.WorkersOnMinerals--;
				base.Execute(bo);
				OnProductionStart(bo);
				bo.AddAction(state.Time + BuildTime, new ActionGeneric(EventName, delegate(IBuildOrder ibo)
				{
					OnProductionFinished(ibo);
				}));
			}
			else if (state.WorkersOnGas > 0)
			{
				state.WorkersOnGas--;
				base.Execute(bo);
				OnProductionStart(bo);
				bo.AddAction(state.Time + BuildTime, new ActionGeneric(EventName, delegate(IBuildOrder ibo)
				{
					OnProductionFinished(ibo);
				}));
			}
			else throw new InvalidActionException();
			state.Drone--;
			state.Food--;
		}

		public virtual void OnProductionFinished(IBuildOrder bo)
		{
			ZergState.ZergBuilding building = GetBuilding(bo.State as ZergState);
			if (building != null)
				building.Built();
		}
		public virtual void OnProductionStart(IBuildOrder bo)
		{
			ZergState.ZergBuilding building = GetBuilding(bo.State as ZergState);
			if (building != null)
				building.Building++;
		}
		private IAction[,] m_Inputs;
		public override IAction[,] Inputs
		{
			get
			{
				if (m_Inputs == null)
					m_Inputs = new IAction[,] { { ActionProduceDrone.Instance } };
				return m_Inputs;
			}
		}
	}
}
